<?php
namespace app\admin\controller\Sys\middleware;
use app\admin\controller\Sys\model\Application;
use Webman\MiddlewareInterface;
use think\facade\Db;
use Webman\Http\Response;
use Webman\Http\Request;

class createTable implements  MiddlewareInterface
{
	
    public function process(Request $request, callable $handler) : Response
    {	
		$data = $request->post();
		
		$connect = $data['connect'] ? $data['connect'] : config('database.default');
		$prefix = config('database.connections.'.$connect.'.prefix');
		
		if(config('database.connections.'.$connect.'.type') <> 'mysql'){
			return $handler($request);
		}
		
		if($data['create_table'] && $data['table_name'] && $data['pk']){
			$table_name = strtolower(trim($data['table_name']));
			$pk = strtolower(trim($data['pk']));

			$sql=" CREATE TABLE IF NOT EXISTS `".config('database.connections.'.$connect.'.prefix')."".$table_name."` ( ";
			$sql .= '
				`'.$pk.'` int(11) NOT NULL AUTO_INCREMENT ,
				PRIMARY KEY (`'.$data['pk'].'`)
				) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COMMENT="'.$data['title'].'";
			';
			Db::connect($connect)->execute($sql);
			if($data['page_type'] == 2){
				Db::connect($connect)->execute("ALTER TABLE `".$prefix.$data['table_name']."` ADD `name` VARCHAR( 50 ) NOT NULL ,ADD `data` TEXT NOT NULL AFTER `name`");
			}
		}
        
		 return $handler($request);
    }
}